#include "OrderedMessage.h"
#include <sstream>
#include <memory>
#include <iostream>
#include <cassert>



namespace streamdb {

OrderedMessage OrderedMessage::Null;

std::string OrderedMessage::toString() const {
    std::ostringstream oss;
    oss << id << ":" << body;
    return oss.str();
}


Status OrderedMessage::toBinary(std::string & bin) const{
    if(this != &Null){
        bin.append(std::to_string(id));
        bin.append(":");
        bin.append(body);
    }
    return Status::OK();
}


//123:abc  assert [id = 123; body = abc]
// ""   assert[InvalidArgument]
// 123  assert[InvalidArgument]
// :  | :abc   assert[InvalidArgument]
// 123:  assert[id=123, body = ""]
Status OrderedMessage::fromBinary(const std::string & bin) {
    if(this == &Null){
        return Status::OK();
    }

    if(bin.empty())
        return Status::InvalidArgument("binary size == 0");

    auto pos = bin.find(":");
    if(pos != std::string::npos){
        if(0 == pos){
            return Status::InvalidArgument("no id of bin-> [:xxxx]");
        }
        id = std::stoll(bin.substr(0, pos));
        body = bin.substr(pos + 1, bin.size() - pos - 1);
        return Status::OK();
    }
    return Status::InvalidArgument();
}


}//namespace streamdb
